<template>
  <div class="searchHistory">
<!-- 搜索建议 -->
<van-cell @click="onSearch (item)" v-for="item in suggestions" :key="item" :title="item" icon="search" >
<!-- <van-cell title="搜索建议" icon="search" />
<van-cell title="搜索建议" icon="search" /> -->
<!-- 搜索框某个值高亮 -->
  <template #title>
  <div v-html="highText(item)"></div>
  </template>
  </van-cell>
    </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  beforeDestroy () {
    clearTimeout(this.setid)// 清除计时器
  },
  watch: {
    searchText: {
      immediate: true, // 首次监听
      async handler (newVal) { // 监听数据变化
        if (this.setid) {
          clearTimeout(this.setid)
        }
        this.setid = setTimeout(async () => {
          console.log(newVal)
          const res = await getSearchSuggestion(newVal)
          console.log(res)
          this.suggestions = res.options
          console.log(newVal)
          console.log('获取联想建议')
        }, 700)
      }
    }
  },
  data () {
    return {
      suggestions: []
    }
  },

  created () {

  },

  methods: {
    highText (item) {
      // 高亮
      const replaceStr = '<span style="color:red">' + this.searchText + '</span>'
      // 把所有匹配的值都高亮 用正则
      // replace:参数1：要替换的内容 参数2：替换后的文本
      const reg = new RegExp(this.searchText, 'gi')// gi的g是固定的全局写死了 i是既可以替换大写也可以替换小写
      // return item.replace(this.searchText, replaceStr)
      return item.replace(reg, replaceStr)
    },
    // 点击搜索
    onSearch (item) {
      this.$emit('onSearch', item)// 和注册事件前面一个样
    }
  }
}
</script>

<style scoped lang='less'>

</style>
